package com.liflag.music.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liflag.music.model.AppSong;
import com.liflag.music.service.AppSongService;
import com.liflag.music.util.KuwoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author dafeiyu
 * @date Created in 2021/6/25,0025.
 */
@RestController
@CrossOrigin
@RequestMapping("/api")
public class AppMusicController {

    @Autowired
    AppSongService songService;

    @RequestMapping("/music")
    String addSong(@RequestParam("callback")String callback, @RequestParam("types")String types,
                   @RequestParam(value = "id",required = false)String id,@RequestParam(value = "name",required = false)String name,
                   @RequestParam(value = "pages",required = false)String pages,
                   @RequestParam(value = "source",required = false)String source) throws Exception {
        HashMap map = new HashMap();
        if(types.equals("url")){        //获取歌曲链接
            JSONObject js = KuwoUtil.getMusicUrl2(id);
            map.put("url",js.get("url"));
            String result = JSON.toJSONString(map);
            return callback+"("+result+")";
        }else if(types.equals("playlist")){
            HashMap playlist = songService.querySongList(id);
            List<HashMap> tracks = songService.queryByListId(id);
            playlist.put("tracks",tracks);
            map.put("playlist",playlist);
            String result = JSON.toJSONString(map);
            return callback+"("+result+")";
        }else if(types.equals("search")){
            JSONArray tracks = null;
            if(source.equals("kugou")){
                tracks = songService.getByKey(name,pages);
            }
            String result = JSON.toJSONString(tracks);
            return callback+"("+result+")";

        }else if(types.equals("userlist")){

        }else if(types.equals("lyric")){//获取歌词
            JSONObject js = KuwoUtil.getLrc(id);
            JSONArray array = js.getJSONArray("lrclist");
            map.put("lyric",array);
        }else if(types.equals("pic")){
            AppSong song = songService.queryByMid(Integer.valueOf(id));
            map.put("url",song.getPic());
        }
        String result = JSON.toJSONString(map);
        return callback+"("+result+")";
    }
}
